package com.rran.study.chat.server.core;

import com.rran.study.chat.server.core.model.AcceptBean;
import com.rran.study.chat.server.core.repository.AcceptRespository;
import com.rran.study.chat.server.core.annotations.Accept;
import com.rran.study.chat.server.core.annotations.AcceptMapping;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.regex.Pattern;

/**
 * @author yy
 * @Type AcceptPostProcess.java
 * @Desc
 * @date 2020/8/9 16:41
 */
@Component
public class AcceptPostProcess implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        String[] beanNames = applicationContext.getBeanNamesForAnnotation(Accept.class);
        try {
            for (String beanName : beanNames) {
                String baseUrl = "";
                Object bean = applicationContext.getBean(beanName);
                Class<?> clazz = bean.getClass();
                if (clazz.isAnnotationPresent(AcceptMapping.class)) {
                    AcceptMapping acceptMapping = clazz.getAnnotation(AcceptMapping.class);
                    baseUrl = acceptMapping.value();
                }

                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
                    if (!method.isAnnotationPresent(AcceptMapping.class)) {
                        continue;
                    }
                    AcceptMapping acceptMapping = method.getAnnotation(AcceptMapping.class);
                    String regex = ("/" + baseUrl + acceptMapping.value()).replaceAll("/+", "/");
                    Pattern pattern = Pattern.compile(regex);

                    AcceptRespository.addBean(new AcceptBean(bean, method, pattern));
                    System.out.println("mapping " + regex + "," + method);
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
